package com.qf.medicaldoctoradmin.onlineSigning.TeamHomepage.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


/**
 * 对医生过期键进行处理,对应的预约key过期，对应的医生人数-1
 */
@Component
public class DoctorSignupListener implements MessageListener {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    // 重写JedisPubSub接口中的onMessage方法，用于处理从Redis接收到的消息
    public void onMessage(Message message, byte[] pattern) {
        // 将pattern字节数组转换为字符串
        String channel = new String(pattern);
        // 检查接收到的channel是否为键过期事件
        if (channel.equals("__keyevent@0__:expired")) {
            // 将接收到的消息的channel部分转换为字符串
            String key = new String(message.getChannel());
            // 检查key是否以"doctor:"开头，即是否是医生签约人数的键
            if (key.startsWith("doctor:")) {
                // 从key中提取医生ID
                String[] split = key.split(":");
                int doctorId = Integer.parseInt(split[1]);
                // 构建医生签约人数的键
                String signupsKey = "doctor:" + doctorId + ":signups";
                // 减少医生的签约人数
                redisTemplate.opsForValue().decrement(signupsKey);
                // 输出日志，通知医生签约人数已减少
                System.out.println("Doctor " + doctorId + " signup count decreased due to key expiration.");
            }
        }
    }
}
